// 添加商品-业务模块
console.log( '添加商品-业务模块。。。' )

import './islogin.js'

/* import axios from "axios"

// 保存当前页面地址
localStorage.setItem('page_url',location.href)

// 获取token
let token = localStorage.getItem('token')

let username = document.querySelector('.username')

// 判断是否已登录
axios({
    method: 'get',
    url: 'http://localhost:8080/users/islogin',
    headers: {
        // 在请求头携带token到后端
        authorization: token
    }
})
.then((res)=>{
    let {data} = res
    if (data.code === 1) {
        // 已登录，显示已登录的账号
        username.innerText = data.data.user
    }
    else{
        // 未登录，跳转到登录页
        location.href = './login.html'
    }
})

// 点击展开下拉菜单
let menu2 = document.querySelector('.menu2')
username.onclick = function (e){
    e.stopPropagation()// 阻止事件传播
    menu2.style.display = 'block'
}
document.onclick = function (){
    menu2.style.display = 'none'
}

// 退出登录
let logout = document.querySelector('.logout')
logout.onclick = function (){
    // 删除本地的token
    localStorage.removeItem('token')
    alert('退出成功！')
    location.reload()
} */

import axios from "axios"

let form = document.querySelector('#form')
form.onsubmit = function (e){
    // 阻止表单提交
    e.preventDefault()

    // 创建FormData对象
    let fd = new FormData(this)

    // 发送上传文件请求
    axios.post('http://localhost:8080/goods/upload',fd)
    .then((res)=>{
        alert(res.data.msg)
        if (res.data.code === 1) {
            // 上传成功，将上传后的图片地址显示在页面中
            let imgurl = document.querySelector('#imgurl')
            imgurl.value = res.data.imgurl
        }
    })
}

let add = document.querySelector('.btn-success')
add.onclick = function (){
    // 获取输入的数据
    let name = document.querySelector('#name').value
    let desc = document.querySelector('#desc').value
    let price = document.querySelector('#price').value
    let type = document.querySelector('#type').value
    let imgurl = document.querySelector('#imgurl').value

    // 空值判断
    if (!name || !desc || !price || !type || !imgurl) {
        alert('输入内容不能为空！')
        return
    }

    // 发送添加商品请求
    axios.post('http://localhost:8080/goods/add',{
        name,
        desc,
        price,
        type,
        imgurl
    })
    .then((res)=>{
        alert(res.data.msg)
        if (res.data.code === 1) {
            // 添加成功，清空输入框
            document.querySelector('#name').value = ''
            document.querySelector('#desc').value = ''
            document.querySelector('#price').value = ''
            document.querySelector('#type').value = ''
            document.querySelector('#imgurl').value = ''
            document.querySelector('#file').value = ''
        }
    })
}
